import axios from 'axios'
import { baseURL } from "@/const"
import { Message } from 'element-ui'

const baseurl = baseURL
// create an axios instance
// Vue.prototype.axios = axios
axios.defaults.timeout = 5000

const service = axios.create({
  baseURL: baseurl, // url = base url + request url
  timeout: 10000 // request timeout
})

export const uploadUrl = `${baseurl}/file/upload`

// request interceptor
service.interceptors.request.use(
  config => {
    // console.log(localStorage.getItem("token"))
      config.headers['token'] = localStorage.getItem("token")
      config.headers['Content-Type'] = 'application/json; charset=UTF-8'
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    // console.log('request.js -> response : ', response);
    const res = response.data
    if (response.config.responseType === 'blob') {
      console.log(response.data)
      return response.data
    }
    if (res.code !== '') {
      const tokenerr = [401, 500, '401', '500']
      const codeStatus = [12028, 12029, '12028', '12029']

      if (tokenerr.includes(res.code)) {
        Message({
          message: res.msg,
          type: 'success',
          duration: 1 * 1000
        })
        // localStorage.clear()
        // location.reload()

      } else if (codeStatus.includes(res.code)) {
        Message({
          message: res.desc,
          type: 'success',
          duration: 1 * 1000
        })
      } else if (res.code == 500) {
        Message({
          message: res.msg,
          type: 'success',
          duration: 1 * 1000
        })
      } else {
        return res
      }
    } else {
      Message({
        message: res.msg,
        type: 'success',
        duration: 1 * 1000
      })
      return res
    }
  },
  error => {
    if (!error.message.includes('timeout')) {
      Message({
        message: '服务器暂无响应，请稍后重试',
        type: 'success',
        duration: 5 * 1000
      })
    }
    return Promise.reject(error)
  }
)

export default service
